<template>
  <div class="container">
    <!-- 页面主标题 -->
    <h1 class="main-title">医疗驾驶舱</h1>

    <el-col :span="6" class="side-panel left-panel draggable">
      <el-card class="info-card" shadow="hover">
        <div slot="header">
          <span>患者信息</span>
        </div>
        <el-form :model="patientInfo" label-width="80px" class="info-form">
          <el-form-item label="姓名">
            <span>{{ patientInfo.name }}</span>
          </el-form-item>
          <el-form-item label="年龄">
            <span>{{ patientInfo.age }}</span>
          </el-form-item>
          <el-form-item label="性别">
            <span>{{ patientInfo.gender }}</span>
          </el-form-item>
          <el-form-item label="病历号">
            <span>{{ patientInfo.medicalRecordId }}</span>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>

    <!-- 训练时间显示 -->
    <div class="training-time">
      <span>训练时长 {{ trainingTime }} 秒</span>  <!-- 显示训练时间 -->
    </div>

    <!-- 步速折线图 -->
    <div class="step-speed-chart">
      <canvas id="speedChart" width="400" height="200"></canvas> <!-- 用于显示步速的图表 -->
    </div>

    <!-- 3D模型展示区域 -->
    <div ref="container" class="three-container"></div>
  </div>
</template>

<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { ElCard, ElRow, ElCol, ElForm, ElFormItem } from 'element-plus';
import Chart from 'chart.js/auto';  // 引入 Chart.js 用于绘制折线图

export default {
  name: 'MedicalDashboard',
  components: {
    ElCard,
    ElRow,
    ElCol,
    ElForm,
    ElFormItem,
  },
  data() {
    return {
      // 患者信息数据
      patientInfo: {
        name: '彭于晏',
        age: 15,
        gender: '男',
        medicalRecordId: 'MR2456716',
      },
      // 训练时间数据
      trainingTime: 0,
      // 步速数据（示例数据）
      stepSpeeds: [0, 1, 2, 3, 2, 3, 4, 3,2,3,3],
    };
  },
  mounted() {
    // 页面加载时，初始化Three.js、计时器和图表
    this.initThreeJS();
    this.enableDrag();
    this.startTrainingTimer();
    this.initSpeedChart();
  },
  methods: {
    // 初始化Three.js场景
    initThreeJS() {
      this.scene = new THREE.Scene();
      this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      this.camera.position.set(0, 1, 2.5);

      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.renderer.setPixelRatio(window.devicePixelRatio);
      this.renderer.setClearColor(0x000000, 0);
      this.$refs.container.appendChild(this.renderer.domElement); // 将渲染器添加到页面

      // 添加光源
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
      this.scene.add(ambientLight);
      const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      directionalLight.position.set(5, 5, 5).normalize();
      this.scene.add(directionalLight);

      // 加载背景图
      const loader = new THREE.TextureLoader();
      loader.load('file/R.jpg', (texture) => {
        this.scene.background = texture;
      });

      // 加载GLTF模型
      const gltfLoader = new GLTFLoader();
      gltfLoader.load('file/glb/Xbot.glb', (gltf) => {
        this.model = gltf.scene;
        this.scene.add(this.model);
        this.model.scale.set(1, 1, 1);
        this.model.position.set(0, -0.7, 0);
        this.mixer = new THREE.AnimationMixer(this.model);
        gltf.animations.forEach((clip) => {
          if (clip.name.toLowerCase().includes('walk')) {
            this.mixer.clipAction(clip).play(); // 播放步态动画
          }
        });
      }, undefined, (error) => {
        console.error('模型加载失败', error);
      });

      // 初始化相机控制器
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = true;
      this.controls.dampingFactor = 0.25;
      this.controls.screenSpacePanning = false;

      // 渲染场景
      const animate = () => {
        requestAnimationFrame(animate);
        if (this.mixer) {
          this.mixer.update(0.01);
        }
        this.controls.update();
        this.renderer.render(this.scene, this.camera);
      };
      animate();

      // 监听窗口大小变化，调整相机和渲染器
      window.addEventListener('resize', () => {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(window.innerWidth, window.innerHeight);
      });
    },

    // 拖拽功能
    enableDrag() {
      const panel = document.querySelector('.draggable');
      let isDragging = false;
      let offsetX, offsetY;

      panel.addEventListener('mousedown', (event) => {
        isDragging = true;
        offsetX = event.clientX - panel.offsetLeft;
        offsetY = event.clientY - panel.offsetTop;
        panel.style.position = 'absolute';
        panel.style.cursor = 'move';
      });

      document.addEventListener('mousemove', (event) => {
        if (isDragging) {
          panel.style.left = `${event.clientX - offsetX}px`;
          panel.style.top = `${event.clientY - offsetY}px`;
        }
      });

      document.addEventListener('mouseup', () => {
        isDragging = false;
        panel.style.cursor = 'default';
      });
    },

    // 启动训练计时器
    startTrainingTimer() {
      setInterval(() => {
        this.trainingTime += 1;  // 每秒增加1秒
      }, 1000);
    },

    // 初始化步速折线图
    initSpeedChart() {
      const ctx = document.getElementById('speedChart').getContext('2d');
      new Chart(ctx, {
        type: 'line',
        data: {
          labels: Array.from({ length: this.stepSpeeds.length }, (_, i) => `步数 ${i + 1}`), // 图表标签
          datasets: [{
            label: '步速',
            data: this.stepSpeeds,  // 步速数据
            borderColor: '#fff',
            fill: true,  // 不填充颜色
          }],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: {
              beginAtZero: true, // x轴从0开始
              ticks: {
                color: '#fff',
              },
            },
            y: {
              beginAtZero: true, // y轴从0开始
              ticks: {
                color: '#fff',
              },
            },
          },
        },
      });
    },
  },
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

body {
  background-image: url('file/R.jpg');
  background-size: cover;
  background-position: top left;  /* Align the background to the top left */
  background-attachment: fixed;
}

.container {
  display: flex;
  align-items: flex-start;  /* Align the content to the top */
  justify-content: flex-start;  /* Align items to the left */
  height: 100vh;
  width: 100vw;  /* Ensure it takes the full viewport width */
  position: relative;
}

.side-panel {
  position: fixed;  /* Fix the left panel */
  top: 0;
  left: 0;  /* Align the panel to the left */
  bottom: 0;
  z-index: 3;  /* Ensure this panel stays on top */
  pointer-events: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: Arial, sans-serif;
  width: 20%;  /* Adjust the width of the left panel */
}

.left-panel {
  padding: 20px;
}

.info-card {
  background: rgba(255, 255, 255, 0);
  border-radius: 8px;
  width: 100%;
}

.info-form {
  font-size: 16px;
  color: #fff;
  text-align: left;
}

.main-title {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 36px;
  color: #fff;
  font-weight: bold;
  z-index: 5;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.7);
}

.three-container {
  width: 100%;
  height: 100%;
  z-index: 1;
}

.draggable {
  cursor: move;
}

.training-time {
  position: absolute;
  top: 20px;
  right: 80px;
  font-size: 24px;
  color: #fff;
  font-weight: bold;
  z-index: 4; /* Ensure training time stays on top */
}

.step-speed-chart {
  position: absolute;
  bottom: 20px;
  right: 120px;
  width: 400px;
  height: 200px;
  z-index: 4; /* Ensure chart stays on top */
}

.step-speed-chart canvas {
  border: 2px solid #fff;
}
</style>
